﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using V5_EaspLibs;
using System.Reflection;
using System.Web.UI;
using System.IO;
using System.Web;
using System.Net;
using System.Collections;
using V5_EaspLibs.Utility;

namespace V5_FrameWork.Data {
    public class BaseHtmlHelper {
        private BaseConfigHelper BaseConfig = new BaseConfigHelper();
        private BaseTemplateHelper BaseTemplate = new BaseTemplateHelper();
        public BaseHtmlHelper() {
        }
        #region
        /// <summary>
        /// 生成静态文件
        /// </summary>
        /// <param name="templateStaticFile">静态文件</param>
        /// <param name="templateFile">模板文件</param>
        public void CreateControlToHtml(string templateStaticFile, string templateFile) {
            ViewManager vm = new ViewManager();
            Control myControl
                = vm.LoadViewControl("~/Template/" + BaseConfig.TemplateDir + "/" + templateFile);
            string html = vm.RenderView(myControl);
            Easp.Fso.CreateFile(templateStaticFile, html);
        }

        public void CreatePageToHtml(string templateStaticFile, string templateFile) {
            StringWriter output = new StringWriter();
            HttpContext.Current.Server.Execute("~/Template/" + BaseConfig.TemplateDir + "/" + templateFile, output, true);
            string html = output.ToString();
            Easp.Fso.CreateFile(templateStaticFile, html);
        }

        private string httpUrl = "http://" + Easp.Req.GetCurrentFullHost();
        public bool CreatePageHtml(string url, string templateStaticFile, ref string strMsg) {
            try {
                string pageContent = GetPageContent(httpUrl + url, "utf-8");
                if (pageContent.IndexOf("文件“/Template/") > -1 && pageContent.IndexOf("”不存在。") > -1) {
                    strMsg = pageContent;
                    return true;
                }
                Easp.Fso.CreateFile(templateStaticFile, pageContent);
                return true;
            }
            catch (Exception ex) {
                strMsg = ex.Message + "==" + ex.InnerException + "==" + ex.StackTrace;
                return false;
            }
        }

        private string GetPageContent(string url, string pagecode) {
            string result = string.Empty;
            try {
                //编码
                Encoding encode = Encoding.GetEncoding(pagecode);
                //请求URL
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                //设置超时(10秒)
                req.Timeout = 10000;
                //获取Response
                HttpWebResponse rep = (HttpWebResponse)req.GetResponse();
                //创建StreamReader与StreamWriter文件流对象
                StreamReader sr = new StreamReader(rep.GetResponseStream(), encode);
                result = sr.ReadToEnd();
                sr.Close();
                sr.Dispose();
            }
            catch (Exception ex) {
                return ex.Message + "==" + ex.InnerException + "==" + ex.StackTrace;
            }
            return result;
        }

        #endregion


        #region 替换Url
        public string ReplaceFormatUrl(string oldUrl, string label, string value) {
            return Easp.Str.Replace(oldUrl, "${" + label + "}", value);
        }
        #endregion


        #region 生成静态帮助
        /// <summary>
        /// 进度状态
        /// </summary>
        /// <param name="c"></param>
        /// <param name="t"></param>
        public void ProcessBar(int c, int t) {
            HttpContext.Current.Response.Write("<script>setPgb(" + ((c + 1) * 100) / t + ");</script>");
            HttpContext.Current.Response.Flush();
        }
        /// <summary>
        /// 初始化进度
        /// </summary>
        /// <param name="tit"></param>
        /// <param name="IsInit"></param>
        public void SetProcessBar(string tit, bool IsInit) {
            if (IsInit) {
                string strFileName = HttpContext.Current.Request.PhysicalApplicationPath + "\\Includes\\progressbar.html";
                System.IO.StreamReader sr = new System.IO.StreamReader(strFileName, System.Text.Encoding.Default);
                string strHtml = sr.ReadToEnd();
                HttpContext.Current.Response.Write(strHtml);
                sr.Close();
                HttpContext.Current.Response.Flush();
            }
            HttpContext.Current.Response.Write("<script>initPgb('" + tit + "');</script>");
            HttpContext.Current.Response.Flush();
        }
        public void SetProcessMessage(string Msg) {
            HttpContext.Current.Response.Write("<script>setMessageBox('" + Msg + "');</script>");
            HttpContext.Current.Response.Flush();
        }
        #endregion

        #region Decode
        public string UrlDecode(string pageContent) {
            return HttpContext.Current.Server.UrlDecode(pageContent);
        }
        public string UrlEncode(string pageContent) {
            return HttpContext.Current.Server.UrlEncode(pageContent);
        }
        public string HtmlDecode(string pageContent) {
            return HttpContext.Current.Server.HtmlDecode(pageContent);
        }
        public string HtmlEncode(string pageContent) {
            return HttpContext.Current.Server.HtmlEncode(pageContent);
        }
        #endregion


        public string Include(string TemplateDir, string filePath) {
            string Path = "~/Template/" + TemplateDir + "/" + filePath;
            StringBuilder build = new StringBuilder();
            HtmlTextWriter htmlWriter = new HtmlTextWriter(new StringWriter(build));
            UserControl uc = new UserControl();
            Control ctrl = uc.LoadControl(Path);//加载用户定义控件

            string html = string.Empty;
            Page p = new Page();
            p.Controls.Add(ctrl);
            p.RenderControl(htmlWriter);
            htmlWriter.Flush();
            html = build.ToString();
            return html;
        }

        /// <summary>
        /// 生成静态页
        /// </summary>
        /// <param name="url">地址 http://www.xxx.com</param>
        /// <param name="saveFile">生成文件  D:\xxx.html</param>
        public void CreateHtml(string url, string saveFile) {
            Exception ex;
            Encoding code = Encoding.GetEncoding("UTF-8");
            string strHtmlCode = string.Empty;
            StreamReader sr = null;
            WebResponse myTemp = WebRequest.Create(url).GetResponse();
            sr = new StreamReader(myTemp.GetResponseStream(), code);
            try {
                sr = new StreamReader(myTemp.GetResponseStream(), code);
                strHtmlCode = sr.ReadToEnd();
            }
            catch (Exception exception1) {
                ex = exception1;
                throw ex;
            }
            finally {
                sr.Close();
            }
            StreamWriter writerHtml = null;
            try {
                writerHtml = new StreamWriter(saveFile, false, code);
                writerHtml.Write(strHtmlCode);
                writerHtml.Flush();
            }
            catch (Exception exception2) {
                ex = exception2;
                throw ex;
            }
            finally {
                writerHtml.Close();
            }
        }
    }
}
